How do I pull `static final` constants from a Java class into a Clojure namespace?

Posted by Joe Holloway on Stack Overflow See other posts from Stack Overflow or by Joe Holloway
Published on 2010-04-03T18:57:29Z Indexed on 2010/04/03 19:03 UTC
Read the original article Hit count: 197

Filed under:
|

I am trying to wrap a Java library with a Clojure binding. One particular class in the Java library defines a bunch of static final constants, for example:

class Foo {
    public static final int BAR = 0;
    public static final int SOME_CONSTANT = 1;
    ...
}

I had a thought that I might be able to inspect the class and pull these constants into my Clojure namespace without explicitly def-ing each one.

For example, instead of explicitly wiring it up like this:

(def *foo-bar* Foo/BAR)
(def *foo-some-constant* Foo/SOME_CONSTANT)

I'd be able to inspect the Foo class and dynamically wire up *foo-bar* and *foo-some-constant* in my Clojure namespace when the module is loaded.

I see two reasons for doing this:

A) Automatically pull in new constants as they are added to the Foo class. In other words, I wouldn't have to modify my Clojure wrapper in the case that the Java interface added a new constant.

B) I can guarantee the constants follow a more Clojure-esque naming convention

I'm not really sold on doing this, but it seems like a good question to ask to expand my knowledge of Clojure/Java interop.

Thanks

© Stack Overflow or respective owner

Related posts about clojure

Related posts about java-interop